package com.jt.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class ObjectMapperUtil {
    private  static final ObjectMapper MAPPER =new ObjectMapper();

    //把对象转为json
    public static String toJson(Object target){
        try {
            return MAPPER.writeValueAsString(target);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            //将检查异常转为运行异常
            throw new RuntimeException(e);
        }
    }

    //把json转为对象
    public  static <T> T toObject(String json,Class<T> targetClass){
        try {
            return  MAPPER.readValue(json,targetClass);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            //将检查异常转为运行异常
            throw new RuntimeException(e);
        }
    }

}
